package org.csu.mypetstore.web.servlets;

import com.github.wxpay.sdk.WechatOrder;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.OrderService;
import org.csu.mypetstore.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class CheckPaymentServlet extends HttpServlet {
    private static final String PAYMENT = "/WEB-INF/jsp/order/Payment.jsp";
    private static final String VIEW_ORDER = "/WEB-INF/jsp/order/ViewOrder.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        WechatOrder wechatOrder = (WechatOrder) req.getSession().getAttribute("wechatOrder");

        if(!wechatOrder.getStatus()){
            req.setAttribute("payment", "Sorry, you might not have paid the bill.");
            req.getRequestDispatcher(PAYMENT).forward(req, resp);
            return;
        }
        else{
            //订单状态更新
            req.getSession().removeAttribute("wechatOrder");
            req.setAttribute("paySuccess", "Success!");
            OrderService orderService = new OrderServiceImpl();

            HttpSession session = req.getSession();
            Account account = (Account) session.getAttribute("account");
            if(account!=null)
            {
              Cart cart = (Cart) session.getAttribute("cart");
              try {
                  if(cart!=null) {
                      orderService.sendEmail(account, cart);
                  }
              }catch (Exception e)
              {
                  e.printStackTrace();
              }
            }

            Cart cart = new Cart();
            req.getSession().removeAttribute("cart");
            req.getSession().setAttribute("cart",cart);
            CatalogService.clearUpCart((Account) req.getSession().getAttribute("account"));

            int orderId = (int)(req.getSession().getAttribute("orderId"));
            req.getSession().setAttribute("order", orderService.getOrder(orderId));
            req.getSession().removeAttribute("orderId");

            req.getRequestDispatcher(VIEW_ORDER).forward(req, resp);//查看订单
        }
    }
}
